package Robot

import (
	"bytes"
	Request "gitee.com/yebetter/dingding_robot/helper/request"
	"sync"
)

type robotMessage struct {
	Url         string
	AccessToken string
}

var onceRobotApi sync.Once
var apiRobotInterface robotInterface

/**
外部调用
73abadf563160d1dc9c9b8af64c9f93b9e3ce800396dd08a2f20f25f0b622f38
*/
func NewRobotApi(accessToken string) robotInterface {
	onceRobotApi.Do(func() {
		apiRobotInterface = &robotMessage{
			Url:         "https://oapi.dingtalk.com/robot/send",
			AccessToken: accessToken,
		}
	})
	return apiRobotInterface
}

/**
获取基本api接口地址
*/
func (this *robotMessage) baseUrl() string {
	var buf bytes.Buffer
	buf.WriteString(this.Url)
	buf.WriteString("?access_token=")
	buf.WriteString(this.AccessToken)
	str := buf.String()
	buf.Reset()
	return str
}

/**
获取图片地址
@param path string 图片发送的地址
*/
func (this *robotMessage) imagePath(path string) string {
	var buf bytes.Buffer
	buf.WriteString("![screenshot](")
	buf.WriteString(path)
	buf.WriteString(")")
	str := buf.String()
	buf.Reset()
	return str
}

/**
发送图片机器人
在钉钉里面申请自定义机器人
@param path string 图片发送的地址
*/
func (this *robotMessage) SendImage(path string) error {
	url := this.baseUrl()
	httpClict := Request.NewHttpClient()
	//设置header
	headerMap := map[string]string{
		"Content-Type": "application/json;charset=utf-8",
	}
	httpClict.AddHeader(headerMap)
	//设置发送消息
	markdownMap := make(map[string]string)
	markdownMap["title"] = "通知"
	markdownMap["text"] = this.imagePath(path)
	//设置发送模式
	dataParam := make(map[string]interface{})
	dataParam["msgtype"] = "markdown"
	dataParam["markdown"] = markdownMap
	httpClict.Init(url, dataParam)
	var err error
	httpClict.SetSuccessListener(func(identifier string, response *Request.HttpResponse) {

	})
	httpClict.SetErrorListener(func(i string, httpError *Request.HttpError) {
		err = httpError.Error
	})
	httpClict.HttpPostReTryTimeOut()
	return err
}

/**
发送文字消息
在钉钉里面申请自定义机器人
@param msg string 发送的消息内容
*/
func (this *robotMessage) SendMessage(msg string) error {
	url := this.baseUrl()
	httpClict := Request.NewHttpClient()
	//设置header
	headerMap := map[string]string{
		"Content-Type": "application/json;charset=utf-8",
	}
	httpClict.AddHeader(headerMap)
	//设置发送消息
	markdownMap := make(map[string]string)
	markdownMap["content"] = msg
	//设置发送模式
	dataParam := make(map[string]interface{})
	dataParam["msgtype"] = "text"
	dataParam["text"] = markdownMap
	httpClict.Init(url, dataParam)
	var err error
	httpClict.SetSuccessListener(func(identifier string, response *Request.HttpResponse) {

	})
	httpClict.SetErrorListener(func(i string, httpError *Request.HttpError) {
		err = httpError.Error
	})
	httpClict.HttpPostReTryTimeOut()
	return err
}
